package com.sl.au.service.impl;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.HierarchyForMailList;
import com.sl.au.entity.PartBaseInfo;
import com.sl.au.repository.HierarchyRepository;
import com.sl.au.repository.PartBaseInfoRepository;
import com.sl.au.repository.UserRepository;
import com.sl.au.service.HierarchyService;

@Service("HierarchyService")
@Transactional
public class HierarchyServiceImpl extends BaseServiceImpl implements HierarchyService{
	
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	HierarchyRepository hierarchyRepository;
	
	@Autowired
	PartBaseInfoRepository partBaseInfoRepository;
	
	@Autowired
	UserRepository userRepository;
	
	@Resource
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	
	@Override
	public HierarchyRepository getRepository() {
		return this.hierarchyRepository;
	}
	
	@Override
	public List<Map<String, Object>> getNodeMap(List<Hierarchy> node) {
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();
		for (Hierarchy p : node) {
			if (null != p) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", p.getId());
				map.put("parentId", p.getGroupParent());
				
//				if (p.getGroupParent().equals("0")) {
//					String Id = p.getId();
//					if (StringUtils.hasText(Id)) {
//						map.put("name", p.getGroupName());
//					}
//				} else {
//					map.put("name", String.valueOf(p.getGroupOrder())+p.getGroupName());
//				}
				map.put("name", String.valueOf((p.getGroupOrder())/2)+p.getGroupName());
				if (StringUtils.hasText(p.getGroupParent())) {
					map.put("isParent", p.getGroupParent());
				}
				map.put("level", p.getGroupLevel().getExtended1());
				map.put("open", true);
				String iconAddress = p.getIconAddress();
				if(iconAddress == null || iconAddress.equals("")) {
					iconAddress = "/wcsi/img/defaultHierarchy.png";
				}else {
					iconAddress = "/wcsi/"+ iconAddress;
				}
				map.put("icon", iconAddress);
				nodeMap.add(map);
			}
		}
		return nodeMap;
	}


	@Override
	public List<Hierarchy> getAllNodes() {
		List<Hierarchy> nodes = new ArrayList<Hierarchy>();
		nodes = hierarchyRepository.findAllNodes();
		return nodes;
	}
	
	/*********** 获取未绑定节点 *************/
	
	@Override
	public List<Hierarchy> getHierarchyByKey(int start, int length, String key, String orderName, String dir) {
		Page<Hierarchy> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if(StringUtils.hasText(key)) {
			pages = hierarchyRepository.getHierarchyByKey(key, pageable);
		}else {
			pages = hierarchyRepository.getHierarchy(pageable);
		}
		return pages.getContent();
	}

	@Override
	public int getHierarchyByKeyCount(String key) {
		int count = 0;
		if(StringUtils.hasText(key)) {
			count = hierarchyRepository.getHierarchyByKeyCount(key);
		}else {
			count = hierarchyRepository.getHierarchyCount();
		}
		return count;
	}

	/************ 获取子节点 ************/
	
	@Override
	public List<Hierarchy> getChildrenHierarchyByKey(int start, int length, String id, String key, String orderName, String dir) {
		Page<Hierarchy> pages = null;
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if(StringUtils.hasText(key)) {
			pages = hierarchyRepository.findByGroupParentAndKey(id,key, pageable);
		}else {
			pages = hierarchyRepository.findByGroupParent(id,pageable);
		}
		return pages.getContent();
	}
	
	@Override
	public int getChildrenHierarchyByKeyCount(String id, String key) {
		int count = 0;
		Pageable pageable = new PageRequest(0, Integer.MAX_VALUE);
		if(StringUtils.hasText(key)) {
			count =  hierarchyRepository.findByGroupParentAndKey(id,key, pageable).getContent().size();
		}else {
			count =  hierarchyRepository.findByGroupParent(id,pageable).getContent().size();
		}
		return count;
	}
	
	/**********************************/
	
	@Override
	public void deleteNodes(String[] ids) {
		if (ids.length > 0) {
			for (String id : ids) {
				if (StringUtils.hasText(id)) {
					hierarchyRepository.setHierarchy(id);
				}
			}
		}
		cleanPartInfo(ids);
		cleanUser(ids);
	}
	
	/**
	 * 清除部件的组织信息
	 * @param id
	 */
	public void cleanPartInfo(String[] ids) {
		//清除权属部门
		partBaseInfoRepository.deleteHierarchy(ids);
		//清除管理部门
		partBaseInfoRepository.deleteManageHierarchy(ids);
		//清除维护部门
		partBaseInfoRepository.deleteMaintainHierarchy(ids);
	}
	
	/**
	 * 清除用户部件信息
	 * @param ids
	 */
	public void cleanUser(String[] ids) {
		//清除用户部门信息
		userRepository.deleteHierarchy(ids);
	}

	@Override
	public void setHierarchyOrder(String groupParent) {
		List<Hierarchy> hierarchys = hierarchyRepository.getHierarchysByGroupParent(groupParent);
		if(hierarchys != null) {
			Hierarchy hierarchy = null;
			for(int i=0;i<hierarchys.size();i++) {
				hierarchy = hierarchys.get(i);
				hierarchy.setGroupOrder(i*2);
				hierarchyRepository.save(hierarchy);
			}
		}
	}

	@Override
	public String getHierarchyIdentify(String id) {
		Hierarchy hierarchy = hierarchyRepository.findOne(id);
		String identify = hierarchy.getGroupIdentify();
		String parent = hierarchy.getGroupParent();
		if(!"0".equals(parent)) {
			identify = this.getHierarchyIdentify(parent) + identify;
		}
		return identify;
	}

	@Override
	public List<Hierarchy> findByParentId(String parentId) {
		return hierarchyRepository.findByParentId(parentId);
	}

	@Override
	public List<HierarchyForMailList> findHierarchyForMailList(String parentId) {
		List<HierarchyForMailList> lst = new ArrayList<HierarchyForMailList>();
		String sql = "select h.id, h.groupName,((select COUNT(1) from sl_dcms_hierarchy hh where hh.groupParent = h.id) + (select COUNT(1) from sl_au_user u where u.hierarchy = h.id ) )as isNext from sl_dcms_hierarchy h where h.groupParent = '"+parentId+"'";
		lst = jdbcTemplate.query(sql, new BeanPropertyRowMapper(HierarchyForMailList.class));
		return lst;
	}
	
	@Override
	public List<HierarchyForMailList> findHierarchyForMailListByKey(String key) {
		List<HierarchyForMailList> lst = new ArrayList<HierarchyForMailList>();
		String sql = "select h.id, h.groupName,((select COUNT(1) from sl_dcms_hierarchy hh where hh.groupParent = h.id) + (select COUNT(1) from sl_au_user u where u.hierarchy = h.id ) )as isNext from sl_dcms_hierarchy h where h.groupName like '%"+key+"%'";
		lst = jdbcTemplate.query(sql, new BeanPropertyRowMapper(HierarchyForMailList.class));
		return lst;
	}
	@Override
	public List<Map<String, Object>> getNextNode(String id) {
		//参数设置
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		
		List<Map<String, Object>> groupList = new ArrayList<Map<String, Object>>();
		String groupSQL = "SELECT p.id , p.groupName , (select count(1) from sl_dcms_hierarchy pp where pp.groupParent = p.id) as isParent " + 
				" FROM" + 
				" sl_dcms_hierarchy p " + 
				" WHERE p.groupParent = :id "+
				" GROUP BY p.groupOrder asc ";
		groupList = namedParameterJdbcTemplate.queryForList(groupSQL,params);	
		return groupList;
	}
	

}
